import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jiffy/jiffy.dart';
import 'package:safetymonitor/app/core/core.dart';
import '../dialog/exit_tips.dart';


///加强版（新增：isRange（含时间段）新增：showMonthsList（指定月份））  通用高仿（ios或Android）时间滚轮选择器
//   isRange方式：
//   MultiWheelTimePickerTimePeriod.show(
//               initialStartDate: controller.startDate,
//               initialEndDate: controller.endDate,
//               onStartEndConfirm: (start, end) {
//                 controller.startDate = start;
//                 controller.endDate = end;
//                 controller.update();
//                 print("====开始时间: $start");
//                 print("====结束时间: $end");
//               },
//               isRange: true, // 启用时间段选择
//             );

//   不是isRange方式：
//   MultiWheelTimePickerTimePeriod.show(
//         onConfirm: (selectedDate) {
//           controller.initialDate=selectedDate;
//           print("选中的时间: $selectedDate");
//         },
//         initialDate:controller.initialDate,//初始化时间
//         // pattern:'yyyy-MM-dd',  //yyyy-MM-dd HH:mm:ss  yyyy-MM-dd HH:mm yyyy-MM-dd HH yyyy-MM-dd yyyy-MM yyyy 不同ui显示和格式
//         // minYear: 2000,                                               //可以配合minYear/maxYear + showMonthsList + isShowCurrentDay 实现当年当月当日
//         // maxYear: 2030,                                               //可以配合minYear/maxYear + showMonthsList + isShowCurrentDay 实现当年当月当日
//         // fixedDate: DateTime.now(), // 固定时间
//         // isLooping: true, // 启用循环滚动
//         // disabledDate: DateTime(2025, 1, 3),// 禁用的日期限制
//         // showMonthsList:[DateTime.now().month,2,3],//指定显示的月份   可以配合minYear/maxYear + showMonthsList + isShowCurrentDay 实现当年当月当日
//         // isShowCurrentDay:true,//指定一天 (DateTime.now().day)       可以配合minYear/maxYear + showMonthsList + isShowCurrentDay 实现当年当月当日
//       );
class MultiWheelTimePickerTimePeriod extends StatefulWidget {
  const MultiWheelTimePickerTimePeriod({
    this.onStartEndConfirm,
    this.onConfirm,
    super.key,
    this.initialStartDate,
    this.initialEndDate,
    this.initialDate,
    // this.visibleUnits = const ['year', 'month', 'day', 'hour', 'minute', 'second'], 按pattern显示不同UI
    this.minYear = 1900,
    this.maxYear = 2100,
    this.showMonthsList=const [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    this.fixedDate,
    this.disabledDate,
    this.isLooping = false,
    this.pattern = 'yyyy-MM-dd HH:mm:ss',
    this.isRange = false, // 新增参数，控制是否启用时间段选择
    this.isShowCurrentDay = false, // xxxx年xx月DateTime.now().day日  控制是否显示当天（简单实现：不涉及年月 只单独控制一个滚轮）
  });

  ///初始化时间  例子: 2020-01-01 00:00:00 / 2020-01-01
  final String? initialDate;
  final String? initialStartDate;
  final String? initialEndDate;

  /// 显示年、月、日、时、分  ->按pattern显示不同UI
  // final List<String> visibleUnits;

  /// 最小年份
  final int minYear;

  /// 最大年份
  final int maxYear;
  /// 新增的参数，用来指定显示的月份 [DateTime.now().month,3,4] 可一个  可多个
  final List<int> showMonthsList;

  /// 固定时间为 null，允许滚动
  final DateTime? fixedDate;

  /// 禁用的日期限制
  final DateTime? disabledDate;

  /// 启用循环滚动
  final bool isLooping;
  ///  用户选择后触发的回调  isRange：false时回调
  final void Function(String)? onConfirm;
  ///  用户选择后触发的回调  修改回调为两个参数：开始时间和结束时间   isRange：true时回调
  final void Function(String, String)? onStartEndConfirm;
  /// 格式
  final String pattern;
  /// 是否启用时间段选择
  final bool isRange;
  ///  xxxx年xx月DateTime.now().day日  控制是否显示当天（简单实现：不涉及年月 只单独控制一个滚轮）
  final bool isShowCurrentDay;

  static void show({
    void Function(String, String)? onStartEndConfirm,
    void Function(String)? onConfirm,
    BuildContext? context,
    String? initialDate,
    // List<String> visibleUnits = const ['year', 'month', 'day', 'hour', 'minute', 'second'], 按pattern显示不同UI
    int minYear = 1900,
    int maxYear = 2100,
    List<int> showMonthsList=const [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    DateTime? fixedDate,
    DateTime? disabledDate,
    bool isLooping = false,
    String pattern = 'yyyy-MM-dd HH:mm:ss',
    bool isRange = false, // 控制是否启用时间段选择
    String? initialStartDate,
    String? initialEndDate,
    bool isShowCurrentDay = false,// xxxx年xx月DateTime.now().day日  控制是否显示当天（简单实现：不涉及年月 只单独控制一个滚轮）

  }) {
    showModalBottomSheet(
      //isScrollControlled 参数，决定了底部弹出菜单的高度是否由内容的高度决定。
      isScrollControlled: isRange,
      context: context ?? Get.context!,
      builder: (_) => MultiWheelTimePickerTimePeriod(
        onStartEndConfirm: onStartEndConfirm,
        onConfirm: onConfirm,
        initialDate: initialDate,
        // visibleUnits: visibleUnits,
        minYear: minYear,
        maxYear: maxYear,
        fixedDate: fixedDate,
        disabledDate: disabledDate,
        isLooping: isLooping,
        pattern: pattern,
        isRange: isRange,
        initialStartDate: initialStartDate,
        initialEndDate: initialEndDate,
        showMonthsList: showMonthsList,
        isShowCurrentDay: isShowCurrentDay,
      ),
    );
  }

  @override
  _MultiWheelTimePickerTimePeriodState createState() => _MultiWheelTimePickerTimePeriodState();
}

class _MultiWheelTimePickerTimePeriodState extends State<MultiWheelTimePickerTimePeriod> {
  late int selectedStartYear, selectedStartMonth, selectedStartDay, selectedStartHour, selectedStartMinute, selectedStartSecond;
  late int selectedEndYear, selectedEndMonth, selectedEndDay, selectedEndHour, selectedEndMinute, selectedEndSecond;
  DateTime currentDateTime = DateTime.now();
  /// 显示年、月、日、时、分
  List<String> visibleUnits= const ['year', 'month', 'day', 'hour', 'minute', 'second'];
  @override
  void initState() {
    super.initState();
    if (widget.fixedDate != null) {
      selectedStartYear = selectedEndYear = widget.fixedDate!.year;
      selectedStartMonth = selectedEndMonth = widget.fixedDate!.month;
      selectedStartDay = selectedEndDay = widget.fixedDate!.day;
      selectedStartHour = selectedEndHour = widget.fixedDate!.hour;
      selectedStartMinute = selectedEndMinute = widget.fixedDate!.minute;
      selectedStartSecond = selectedEndSecond = widget.fixedDate!.second;
    } else {
      _initializeSelectedDate();
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Container(
        color: Colors.white,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildHeader(),
            if (widget.isRange) ...[
              Text('开始时间', style: TextStyle(fontSize: 16.sp)),
              SizedBox(height: 5.w),
              _buildTimePicker('start'),
              SizedBox(height: 10.w),
              Text('结束时间', style: TextStyle(fontSize: 16.sp)),
              SizedBox(height: 5.w),
              _buildTimePicker('end'),
            ] else ...[
              SizedBox(height: 5.w),
              _buildTimePicker('single'),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildTimePicker(String type) {
    return SizedBox(
      height: 200.w,
      child: Row(
        children:visibleUnits.map((unit) => Expanded(child: _buildPicker(unit, type))).toList(),
      ),
    );
  }

  Widget _buildPicker(String unit, String type) {
    if (widget.fixedDate != null) {
      return Center(
        child: Text(
          _formatFixedValue(unit),
          style: TextStyle(fontSize: 16.sp),
        ),
      );
    }

    int selectedYear, selectedMonth, selectedDay, selectedHour, selectedMinute, selectedSecond;
    if (type == 'start') {
      selectedYear = selectedStartYear;
      selectedMonth = selectedStartMonth;
      selectedDay = selectedStartDay;
      selectedHour = selectedStartHour;
      selectedMinute = selectedStartMinute;
      selectedSecond = selectedStartSecond;
    } else if (type == 'end') {
      selectedYear = selectedEndYear;
      selectedMonth = selectedEndMonth;
      selectedDay = selectedEndDay;
      selectedHour = selectedEndHour;
      selectedMinute = selectedEndMinute;
      selectedSecond = selectedEndSecond;
    } else {
      selectedYear = selectedStartYear;
      selectedMonth = selectedStartMonth;
      selectedDay = selectedStartDay;
      selectedHour = selectedStartHour;
      selectedMinute = selectedStartMinute;
      selectedSecond = selectedStartSecond;
    }

    int itemCount;
    FixedExtentScrollController controller;
    // itemBuilder下:比较年、月、日、时、分、秒，确保每个单位的滚动项正确禁用。如果某一项的值大于禁用日期的对应值，则该项被禁用并显示为灰色
    switch (unit) {
      case 'year':
        itemCount = widget.maxYear - widget.minYear + 1;
        controller = FixedExtentScrollController(
          //为项目大小相同的滚动条创建滚动控制器。
          initialItem: selectedYear - widget.minYear,
        );
        return _buildCupertinoPicker(
          itemCount: itemCount,
          controller: controller,
          isLooping: widget.isLooping,
          unit: unit,
          onSelectedItemChanged: (index) {
            setState(() {
              if (type == 'start') {
                selectedStartYear = widget.minYear + index; // 更新选中年份
              } else if (type == 'end') {
                selectedEndYear = widget.minYear + index; // 更新选中年份
              } else {
                selectedStartYear = widget.minYear + index; // 更新选中年份
              }
            });
          },
          itemBuilder: (index) {
            final int year = widget.minYear + index;
            final bool isDisabled = widget.disabledDate != null && year > widget.disabledDate!.year;
            return _buildPickerItem('$year年', isDisabled); // 显示年
          },
        );
      case 'month':
      // 过滤掉无效的月份（小于1或大于12的月份）
      //   final validMonthsList = widget.showMonthsList
      //       .where((month) => month >= 1 && month <= 12)  // 只保留1到12之间的月份
      //       .toList();
      // 只显示 showMonthsList 中的月份
        itemCount = widget.showMonthsList.length;  // 根据传入的月份列表长度来设置项的数量
        controller = FixedExtentScrollController(
          initialItem: selectedMonth - 1,
        );

        return _buildCupertinoPicker(
          itemCount: itemCount,  // 设置为 showMonthsList 的长度
          controller: controller,
          isLooping: widget.isLooping,
          unit: unit,
          onSelectedItemChanged: (index) {
            setState(() {
              final selectedMonth = widget.showMonthsList[index]; // 获取当前选择的月份
              if (type == 'start') {
                selectedStartMonth = selectedMonth;
              } else if (type == 'end') {
                selectedEndMonth = selectedMonth;
              } else {
                selectedStartMonth = selectedMonth;
              }
            });
          },
          itemBuilder: (index) {
            final int month = widget.showMonthsList[index];  // 获取该项对应的月份
            final bool isDisabled = widget.disabledDate != null &&
                (selectedYear > widget.disabledDate!.year ||
                    (selectedYear == widget.disabledDate!.year && month > widget.disabledDate!.month));
            return _buildPickerItem('$month月', isDisabled);
          },
        );
      case 'day':
        if(!widget.isShowCurrentDay){
          itemCount = _getDaysInMonth(selectedYear, selectedMonth);
          controller = FixedExtentScrollController(
            initialItem: selectedDay - 1,
          );
          return _buildCupertinoPicker(
            itemCount: itemCount,
            controller: controller,
            isLooping: widget.isLooping,
            unit: unit,
            onSelectedItemChanged: (index) {
              setState(() {
                if (type == 'start') {
                  selectedStartDay = index + 1;
                } else if (type == 'end') {
                  selectedEndDay = index + 1;
                } else {
                  selectedStartDay = index + 1;
                }
              });
            },
            itemBuilder: (index) {
              final int day = index + 1;
              final bool isDisabled = widget.disabledDate != null &&
                  (selectedYear > widget.disabledDate!.year ||
                      (selectedYear == widget.disabledDate!.year && selectedMonth > widget.disabledDate!.month) ||
                      (selectedYear == widget.disabledDate!.year && selectedMonth == widget.disabledDate!.month && day > widget.disabledDate!.day));
              return _buildPickerItem('$day日', isDisabled);
            },
          );
        }else{
          controller = FixedExtentScrollController(
            initialItem: 0,
          );
          return _buildCupertinoPicker(
            itemCount: 1,
            controller: controller,
            isLooping: widget.isLooping,
            unit: unit,
            onSelectedItemChanged: (index) {
              setState(() {
                if (type == 'start') {
                  selectedStartDay = currentDateTime.day;
                } else if (type == 'end') {
                  selectedEndDay  = currentDateTime.day;
                } else {
                  selectedStartDay  = currentDateTime.day;
                }
              });
            },
            itemBuilder: (index) {
              final int day = currentDateTime.day;
              final bool isDisabled = widget.disabledDate != null &&
                  (selectedYear > widget.disabledDate!.year ||
                      (selectedYear == widget.disabledDate!.year && selectedMonth > widget.disabledDate!.month) ||
                      (selectedYear == widget.disabledDate!.year && selectedMonth == widget.disabledDate!.month && day > widget.disabledDate!.day));
              return _buildPickerItem('$day日', isDisabled);
            },
          );
        }
      case 'hour':
        itemCount = 24;
        controller = FixedExtentScrollController(
          initialItem: selectedHour,
        );
        return _buildCupertinoPicker(
          itemCount: itemCount,
          controller: controller,
          isLooping: widget.isLooping,
          unit: unit,
          onSelectedItemChanged: (index) {
            setState(() {
              if (type == 'start') {
                selectedStartHour = index;
              } else if (type == 'end') {
                selectedEndHour = index;
              } else {
                selectedStartHour = index;
              }
            });
          },
          itemBuilder: (index) {
            final bool isDisabled = widget.disabledDate != null &&
                (selectedYear > widget.disabledDate!.year ||
                    (selectedYear == widget.disabledDate!.year && selectedMonth > widget.disabledDate!.month) ||
                    (selectedYear == widget.disabledDate!.year && selectedMonth == widget.disabledDate!.month && selectedDay > widget.disabledDate!.day) ||
                    (selectedYear == widget.disabledDate!.year && selectedMonth == widget.disabledDate!.month && selectedDay == widget.disabledDate!.day && index > widget.disabledDate!.hour));
            return _buildPickerItem('$index时', isDisabled);
          },
        );
      case 'minute':
        itemCount = 60;
        controller = FixedExtentScrollController(
          initialItem: selectedMinute,
        );
        return _buildCupertinoPicker(
          itemCount: itemCount,
          controller: controller,
          isLooping: widget.isLooping,
          unit: unit,
          onSelectedItemChanged: (index) {
            setState(() {
              if (type == 'start') {
                selectedStartMinute = index;
              } else if (type == 'end') {
                selectedEndMinute = index;
              } else {
                selectedStartMinute = index;
              }
            });
          },
          itemBuilder: (index) {
            final bool isDisabled = widget.disabledDate != null &&
                (selectedYear > widget.disabledDate!.year ||
                    (selectedYear == widget.disabledDate!.year && selectedMonth > widget.disabledDate!.month) ||
                    (selectedYear == widget.disabledDate!.year && selectedMonth == widget.disabledDate!.month && selectedDay > widget.disabledDate!.day) ||
                    (selectedYear == widget.disabledDate!.year && selectedMonth == widget.disabledDate!.month && selectedDay == widget.disabledDate!.day && selectedHour > widget.disabledDate!.hour) ||
                    (selectedYear == widget.disabledDate!.year &&
                        selectedMonth == widget.disabledDate!.month &&
                        selectedDay == widget.disabledDate!.day &&
                        selectedHour == widget.disabledDate!.hour &&
                        index > widget.disabledDate!.minute));
            return _buildPickerItem('$index分', isDisabled);
          },
        );
      case 'second':
        itemCount = 60;
        controller = FixedExtentScrollController(
          initialItem: selectedSecond,
        );
        return _buildCupertinoPicker(
          itemCount: itemCount,
          controller: controller,
          isLooping: widget.isLooping,
          unit: unit,
          onSelectedItemChanged: (index) {
            setState(() {
              if (type == 'start') {
                selectedStartSecond = index;
              } else if (type == 'end') {
                selectedEndSecond = index;
              } else {
                selectedStartSecond = index;
              }
            });
          },
          itemBuilder: (index) {
            final bool isDisabled = widget.disabledDate != null &&
                (selectedYear > widget.disabledDate!.year ||
                    (selectedYear == widget.disabledDate!.year && selectedMonth > widget.disabledDate!.month) ||
                    (selectedYear == widget.disabledDate!.year && selectedMonth == widget.disabledDate!.month && selectedDay > widget.disabledDate!.day) ||
                    (selectedYear == widget.disabledDate!.year && selectedMonth == widget.disabledDate!.month && selectedDay == widget.disabledDate!.day && selectedHour > widget.disabledDate!.hour) ||
                    (selectedYear == widget.disabledDate!.year &&
                        selectedMonth == widget.disabledDate!.month &&
                        selectedDay == widget.disabledDate!.day &&
                        selectedHour == widget.disabledDate!.hour &&
                        selectedMinute > widget.disabledDate!.minute) ||
                    (selectedYear == widget.disabledDate!.year &&
                        selectedMonth == widget.disabledDate!.month &&
                        selectedDay == widget.disabledDate!.day &&
                        selectedHour == widget.disabledDate!.hour &&
                        selectedMinute == widget.disabledDate!.minute &&
                        index > widget.disabledDate!.second));
            return _buildPickerItem('$index秒', isDisabled);
          },
        );
      default:
        return Container();
    }
  }

  ///功能：通用的滚轮选择器。
  // 关键点：
  // itemExtent：设置每个滚轮项的高度。
  // scrollController：用于控制滚动。
  // isLooping：决定是否循环滚动。
  // itemBuilder：动态构建滚轮每一项。
  Widget _buildCupertinoPicker({
    required int itemCount,
    required FixedExtentScrollController controller,
    required bool isLooping,
    required String unit,
    required void Function(int) onSelectedItemChanged,
    required Widget Function(int) itemBuilder,
  }) {
    //CupertinoPicker是Flutter框架中用于实现iOS风格的选择器的组件
    //iOS风格选择器：提供类似iPhone上的滚轮选择器，用户可以通过滚动来选择选项。
    // 自定义子组件：可以包含任意数量的子组件（如文本、图标等），这些子组件会以滚轮形式展示。
    // 响应选择变化：通过onSelectedItemChanged回调函数，可以在用户选择不同项时执行相应操作。
    // 固定高度：默认情况下，CupertinoPicker的高度是固定的，通常为216逻辑像素
    return CupertinoPicker.builder(
      itemExtent: 40,
      // 每项的高度
      scrollController: controller,
      // 控制滚动行为
      onSelectedItemChanged: onSelectedItemChanged,
      // 滚动改变时回调
      childCount: isLooping ? null : itemCount,
      // 如果循环滚动，childCount 设为 null
      itemBuilder: (context, index) {
        if (isLooping) index = index % itemCount; // 循环滚动时，计算实际索引
        return Center(child: itemBuilder(index)); // 构建单项内容
      },
    );
  }

  // 自定义的滚轮选择项显示
  //关键点：
  // 判断是否禁用，禁用的项显示为灰色，正常项显示为黑色。
  // 使用 Text 小部件渲染文字内容。
  Widget _buildPickerItem(String text, bool isDisabled) {
    return Text(
      text,
      style: TextStyle(
        fontSize: 16.sp,
        color: isDisabled ? Colors.grey : Colors.black, // 禁用项显示为灰色
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      color: Colors.grey[200],
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('取消', style: TextStyle(fontSize: 16.sp)),
          ),
          Text('时间选择器', style: TextStyle(fontSize: 18.sp)),
          TextButton(
            onPressed: () {
              final DateTime startDateTime = DateTime(
                selectedStartYear,
                selectedStartMonth,
                selectedStartDay,
                selectedStartHour,
                selectedStartMinute,
                selectedStartSecond,
              );
              final DateTime endDateTime = DateTime(
                selectedEndYear,
                selectedEndMonth,
                selectedEndDay,
                selectedEndHour,
                selectedEndMinute,
                selectedEndSecond,
              );
              // 检查当前选择的时间是否超过禁用时间
              // 定义：判断当前 DateTime 对象是否在另一个 DateTime 对象之后
              if (widget.disabledDate != null && startDateTime.isAfter(widget.disabledDate!)) {
                Get.dialog<bool>(ExitTips(
                  content: '${widget.isRange?'开始时间-':''}当前选择的禁用时间不可用，请选择更早的时间。',
                  func: (v) {
                    if (v) {}
                  },
                ));
                return; // 阻止关闭弹框
              }
              // 检查当前选择的时间是否超过禁用时间
              // 定义：判断当前 DateTime 对象是否在另一个 DateTime 对象之后
              if (widget.isRange&&widget.disabledDate != null && endDateTime.isAfter(widget.disabledDate!)) {
                Get.dialog<bool>(ExitTips(
                  content: '结束时间-当前选择的禁用时间不可用，请选择更早的时间。',
                  func: (v) {
                    if (v) {}
                  },
                ));
                return; // 阻止关闭弹框
              }
              //定义：判断当前 DateTime 对象是否在另一个 DateTime 对象之前。
              if (widget.isRange && endDateTime.isBefore(startDateTime)) {
                Get.dialog<bool>(ExitTips(
                  content: '结束时间不能早于开始时间！',
                  func: (v) {
                    if (v) {}
                  },
                ));
                return;
              }
              if(widget.isRange){
                // if(widget.onStartEndConfirm==null){
                //   AppToast.show('请实现onStartEndConfirm方法');
                //   return;
                // }
                Navigator.of(context).pop();
                widget.onStartEndConfirm!(
                  Jiffy.parseFromDateTime(startDateTime).format(pattern: widget.pattern),
                  Jiffy.parseFromDateTime(endDateTime).format(pattern: widget.pattern),
                );
              }else{
                // if(widget.onConfirm==null){
                //   AppToast.show('请实现onConfirm法');
                //   return;
                // }
                Navigator.of(context).pop();
                widget.onConfirm!(Jiffy.parseFromDateTime(startDateTime).format(pattern: widget.pattern));
              }
            },
            child: Text('确定', style: TextStyle(fontSize: 16.sp)),
          ),
        ],
      ),
    );
  }

  /// 获取有效的初始日期 和 处理禁用的日期限制
  void _initializeSelectedDate() {
    if (!widget.isRange) {
      // 处理初始日期
      DateTime initialDateTime;

      if (widget.initialDate == null || widget.initialDate!.isEmpty) {
        initialDateTime = currentDateTime; // 初始日期为空时使用当前时间
      } else {
        // 预处理 initialDate
        String formattedDate = widget.initialDate!;
        if (widget.pattern == 'yyyy' && !formattedDate.contains('-')) {
          formattedDate = '$formattedDate-01-01'; // 如果只有年份，补充默认的月和日
        } else if (widget.pattern == 'yyyy-MM' && formattedDate.split('-').length == 1) {
          formattedDate = '$formattedDate-01'; // 如果是 "yyyy-MM"，补充默认的日
        }

        // 尝试解析日期
        try {
          initialDateTime = DateTime.parse(formattedDate);
        } catch (e) {
          initialDateTime = currentDateTime; // 解析失败时使用当前时间
        }
      }
      // 初始化选中的日期
      selectedStartYear = selectedEndYear = initialDateTime.year;
      // 处理 只显示这些月份的情况
      if(widget.showMonthsList.isNotEmpty&&widget.showMonthsList.length<12){
        // selectedStartMonth = selectedEndMonth = widget.showMonthsList.first;
        selectedStartMonth = selectedEndMonth = widget.showMonthsList.indexOf(initialDateTime.month)+1;
      }else{
        selectedStartMonth = selectedEndMonth = initialDateTime.month;
      }
      selectedStartDay = selectedEndDay = initialDateTime.day;
      selectedStartHour = selectedEndHour = initialDateTime.hour;
      selectedStartMinute = selectedEndMinute = initialDateTime.minute;
      selectedStartSecond = selectedEndSecond = initialDateTime.second;
      _patternDefaultValueStart();
    } else {
      // 处理初始日期
      DateTime initialDateTime;
      if (widget.initialStartDate == null || widget.initialStartDate!.isEmpty) {
        initialDateTime = currentDateTime; // 初始日期为空时使用当前时间
      } else {
        // 预处理 initialDate
        String formattedDate = widget.initialStartDate!;
        if (widget.pattern == 'yyyy' && !formattedDate.contains('-')) {
          formattedDate = '$formattedDate-01-01'; // 如果只有年份，补充默认的月和日
        } else if (widget.pattern == 'yyyy-MM' && formattedDate.split('-').length == 1) {
          formattedDate = '$formattedDate-01'; // 如果是 "yyyy-MM"，补充默认的日
        }

        // 尝试解析日期
        try {
          initialDateTime = DateTime.parse(formattedDate);
        } catch (e) {
          initialDateTime = currentDateTime; // 解析失败时使用当前时间
        }
      }
      // 初始化选中的日期
      selectedStartYear = initialDateTime.year;
      if(widget.showMonthsList.isNotEmpty&&widget.showMonthsList.length<12){
        selectedStartMonth  = widget.showMonthsList.indexOf(initialDateTime.month)+1;
      }else{
        selectedStartMonth = initialDateTime.month;
      }
      selectedStartDay = initialDateTime.day;
      selectedStartHour = initialDateTime.hour;
      selectedStartMinute = initialDateTime.minute;
      selectedStartSecond = initialDateTime.second;

      _patternDefaultValueStart();

      // 处理初始日期
      DateTime initialDateTimeEnd;

      if (widget.initialEndDate == null || widget.initialEndDate!.isEmpty) {
        initialDateTimeEnd = currentDateTime; // 初始日期为空时使用当前时间
      } else {
        // 预处理 initialDate
        String formattedDate = widget.initialEndDate!;
        if (widget.pattern == 'yyyy' && !formattedDate.contains('-')) {
          formattedDate = '$formattedDate-01-01'; // 如果只有年份，补充默认的月和日
        } else if (widget.pattern == 'yyyy-MM' && formattedDate.split('-').length == 1) {
          formattedDate = '$formattedDate-01'; // 如果是 "yyyy-MM"，补充默认的日
        }

        // 尝试解析日期
        try {
          initialDateTimeEnd = DateTime.parse(formattedDate);
        } catch (e) {
          initialDateTimeEnd = currentDateTime; // 解析失败时使用当前时间
        }
      }
      // 初始化选中的日期
      selectedEndYear = initialDateTimeEnd.year;
      // 处理 只显示这些月份的情况
      if(widget.showMonthsList.isNotEmpty&&widget.showMonthsList.length<12){
        // selectedEndMonth = widget.showMonthsList.first;
        selectedEndMonth  = widget.showMonthsList.indexOf(initialDateTimeEnd.month)+1;
      }else{
        selectedEndMonth = initialDateTimeEnd.month;
      }
      selectedEndDay = initialDateTimeEnd.day;
      selectedEndHour = initialDateTimeEnd.hour;
      selectedEndMinute = initialDateTimeEnd.minute;
      selectedEndSecond = initialDateTimeEnd.second;
      _patternDefaultValueEnd();
    }
  }
  _patternDefaultValueStart(){
    // 根据 pattern 设置具体的默认值
    //-----------------------主要处理disabledDate启用后-------------------------------------
    //  这里就需要考虑pattern 设置默认值
    switch (widget.pattern) {
      case 'yyyy':
        selectedStartMonth = 1;
        selectedStartDay = 1;
        selectedStartHour = 0;
        selectedStartMinute = 0;
        selectedStartSecond = 0;
        visibleUnits= const ['year'];
        break;
      case 'yyyy-MM':
        selectedStartDay = 1;
        selectedStartHour = 0;
        selectedStartMinute = 0;
        selectedStartSecond = 0;
        visibleUnits= const ['year', 'month'];
        break;
      case 'yyyy-MM-dd':
        selectedStartHour = 0;
        selectedStartMinute = 0;
        selectedStartSecond = 0;
        visibleUnits= const ['year', 'month', 'day'];
        break;
      case 'yyyy-MM-dd HH':
        selectedStartMinute = 0;
        selectedStartSecond = 0;
        visibleUnits= const ['year', 'month', 'day', 'hour'];
        break;
      case 'yyyy-MM-dd HH:mm':
        selectedStartSecond = 0;
        visibleUnits= const ['year', 'month', 'day', 'hour', 'minute'];
        break;
      default:
        break; // 默认已经是完整的日期时间格式
    }
  }
  _patternDefaultValueEnd(){
    // 根据 pattern 设置具体的默认值
    //-----------------------主要处理disabledDate启用后-------------------------------------
    //  这里就需要考虑pattern 设置默认值
    switch (widget.pattern) {
      case 'yyyy':
        selectedEndMonth = 1;
        selectedEndDay = 1;
        selectedEndHour = 0;
        selectedEndMinute = 0;
        selectedEndSecond = 0;
        visibleUnits= const ['year'];
        break;
      case 'yyyy-MM':
        selectedEndDay = 1;
        selectedEndHour = 0;
        selectedEndMinute = 0;
        selectedEndSecond = 0;
        visibleUnits= const ['year', 'month'];
        break;
      case 'yyyy-MM-dd':
        selectedEndHour = 0;
        selectedEndMinute = 0;
        selectedEndSecond = 0;
        visibleUnits= const ['year', 'month', 'day'];
        break;
      case 'yyyy-MM-dd HH':
        selectedEndMinute = 0;
        selectedEndSecond = 0;
        visibleUnits= const ['year', 'month', 'day', 'hour'];
        break;
      case 'yyyy-MM-dd HH:mm':
        selectedEndSecond = 0;
        visibleUnits= const ['year', 'month', 'day', 'hour', 'minute'];
        break;
      default:
        break; // 默认已经是完整的日期时间格式
    }
  }

  ///功能：计算指定年份和月份的天数。
  // 逻辑：
  // 利用 Dart 的 DateTime 构造函数，传入下一月的第 0 天，返回当前月的最后一天。
  int _getDaysInMonth(int year, int month) {
    if (month == 12) {
      return DateTime(year + 1, 1, 0).day; // 获取下一年的第0天，即当前年12月的最后一天
    } else {
      return DateTime(year, month + 1, 0).day; // 获取当前年下一个月的第0天，即本月的最后一天
    }
  }

  String _formatFixedValue(String unit) {
    switch (unit) {
      case 'year':
        return '${widget.fixedDate!.year}年';
      case 'month':
        return '${widget.fixedDate!.month}月';
      case 'day':
        return '${widget.fixedDate!.day}日';
      case 'hour':
        return '${widget.fixedDate!.hour}时';
      case 'minute':
        return '${widget.fixedDate!.minute}分';
      case 'second':
        return '${widget.fixedDate!.second}秒';
      default:
        return '';
    }
  }
}
